<template>
  <div>
    <el-form @submit.native.prevent :inline="true" :model="formData">
      <el-form-item>
        <select-address
          v-model="formData.addressCode"
          placeholder="地址查询"
          auto-top
          clearable
          :bottom-level="2"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="formData.month" type="month" placeholder="选择月"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumKeyAreaType"
          clearable
          placeholder="选择区域类型"
          v-model="formData.areaType"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button :loading="loading" icon="el-icon-search" @click="getData()">查询</el-button>
        <el-button :loading="downloadLoading" icon="el-icon-download" @click="onExportExcel()">
          下载
        </el-button>
      </el-form-item>
    </el-form>

    <div class="w-100">
      <el-echarts
        theme="macarons"
        :loading="loading"
        :height="250"
        :option="chartOption"
      ></el-echarts>
    </div>

    <analy-cover-report
      ref="reportCity"
      :address-code="formData.addressCode"
      :area-type="formData.areaType"
      :query-date="formData.month"
      @getData="onGetData"
    ></analy-cover-report>
  </div>
</template>

<script>
import { enumAreaType } from '@/credit/views/city/report/analyMixins'
import { EchartsLinearGradient } from '@vimi/utils-tool'

import SelectAddress from '@/components/select/SelectAddress'
import AnalyCoverReport from '@/credit/views/city/report/AnalyCoverReport'

const areaKeys = {
  0: 'is_9_3',
  1: 'is_assess_county',
  2: 'is_refer_county',
  3: 'is_bus_assess_county',
}
const enumKeyAreaType = enumAreaType.map(it => ({
  ...it,
  value: areaKeys[it.value],
}))

export default {
  components: {
    SelectAddress,
    AnalyCoverReport,
  },
  props: {},
  data() {
    return {
      enumKeyAreaType,
      loading: false,
      downloadLoading: false,
      formData: {
        addressCode: '',
        month: new Date(),
        areaType: '',
      },
      chartOption: {},
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    getData() {
      const ref = this.$refs.reportCity
      if (ref) {
        ref.getData()
      }
    },

    onExportExcel() {
      const ref = this.$refs.reportCity
      if (ref) {
        ref.onExportExcel()
      }
    },

    onGetData(data) {
      const coverageRate = enumKeyAreaType.reduce((p, c) => {
        p[c.value] = { sum: 0, count: 0, percent: 0, label: c.label }
        return p
      }, {})
      const coverageKeys = Object.keys(coverageRate)

      for (const d of data) {
        // 计算覆盖率
        coverageKeys.forEach(key => {
          if (+d[key] === 1) {
            coverageRate[key].sum++
            coverageRate[key].count += +d.all_total > 0 ? 1 : 0
          }
        })
      }

      const xData = []
      const aData = []
      const countData = []
      const sumData = []
      coverageKeys.forEach(key => {
        const item = coverageRate[key]
        const { sum, count } = item
        item.percent = sum > 0 ? Math.round((count / sum) * 1e4) / 1e2 : 1e2
        xData.push(item.label)
        aData.push(item.percent)
        countData.push(count)
        sumData.push(sum)
      })
      this.setOption({
        xData,
        aData,
        countData,
        sumData,
      })
    },

    setOption(data) {
      this.chartOption = {
        title: {
          text: '覆盖率',
          subtext: '',
        },
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            const sum = data.sumData[params.dataIndex] || 0
            const count = data.countData[params.dataIndex] || 0
            return `${params.name}<br>
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#33dbdb;"></span>
            覆盖率：${params.value}% （共覆盖 ${count}/${sum} 个区县）`
          },
        },
        legend: {
          data: ['覆盖率'],
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        grid: {
          top: 80,
          left: 50,
          right: 40,
        },
        xAxis: [
          {
            type: 'category',
            data: data.xData,
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '覆盖率（%）',
          },
        ],
        series: [
          {
            name: '覆盖率（%）',
            type: 'bar',
            barMaxWidth: 60,
            yAxisIndex: 0,
            data: data.aData,
            label: { show: true, position: 'top', formatter: '{c}%' },
            itemStyle: {
              // barBorderRadius: 30,
              color: new EchartsLinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#3AE3D2' },
                { offset: 1, color: '#32DADD' },
              ]),
            },
          },
        ],
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
